<?php

namespace App\Recharge\Api;

use App\Models\InterfaceConfiguration;
use App\Recharge\Bean\ApiNotifyDataBean;
use App\Recharge\Bean\BasicInformation;
use Illuminate\Http\Request;

class Jiumeng extends AbstractApi
{

    /**
     * @inheritDoc
     */
    public function rechargeData(BasicInformation $bean): array
    {
        $type = 0;
        if (preg_match("/^1[34578]\d{9}$/", $bean->getAccount())) {
            $type = 1;
        }
        $array = [
            'merchantId'    => $bean->getSupplierNum(),
            'orderNum'      => $bean->getOrderNo(),//订单号
            'productCode'   => $bean->getGoodsId(), //商品编码
            'chargeAccount' => $bean->getAccount(),
            'buyCount'      => $bean->getRechargeNum() * $bean->getStartCharging(),
            'accountType'   => $type,
            'clientIp'      => $bean->getIp(),
            'callBackUrl'   => $bean->getNotifyUrl(), //异步回调地址
        ];

        ksort($array);
        $sign_key = $array['accountType'].$array['buyCount'].$array['chargeAccount'].$array['merchantId'].$array['orderNum']
            .$array['productCode']. $bean->getSecretKey();
        $array['sign'] = md5($sign_key);

        return $array;
    }

    /**
     * @param InterfaceConfiguration $api
     * @param Request $request
     * @return ApiNotifyDataBean
     */
    public function apiNotifyLogic(InterfaceConfiguration $api, Request $request): ApiNotifyDataBean
    {
        $status = $request->input('orderStatus', '');
        $order_sn = $request->input('orderNum', '');
        return $this->apiNotifyData($order_sn, $status)->setExecute(in_array($status, [1, 2]))->setRechargeSuccess($status == 1);
    }
}
